<template>
  <div style="background-color: white;margin-left: 20px;">
    <!-- 查询框 -->
    <div class="search-wrapper">
      <el-collapse accordion v-model="activeName">
        <el-collapse-item title="查询条件" name="1">
          <el-form ref="form" :model="searchParams" label-width="130px" class="queryForm" :inline="true" size="mini">
            <el-form-item label="单据类型">
              <el-select v-model="searchParams.documentType" placeholder="全部" :clearable="true">
                <el-option label="GIT Invoice" value="GIT Invoice"></el-option>
                <el-option label="Supplier Invoice" value="Supplier Invoice"></el-option>
                <el-option label="General Purchase" value="General Purchase"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="单据号">
              <el-input placeholder="请输入单据号" v-model="searchParams.documentNr" :clearable="true" :maxlength="26">
              </el-input>
            </el-form-item>
            <el-form-item label="是否有效">
              <el-select v-model="searchParams.validState" style="width:100%" :clearable="true">
                <el-option label="失效" value="0"></el-option>
                <el-option label="有效" value="1"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="BG" :maxlength="200">
              <el-input placeholder="请输入BG" v-model="searchParams.bg" :clearable="true"> </el-input>
            </el-form-item>
            <el-form-item label="单据时间" prop="documentDateRange">
              <el-date-picker :clearable="true" v-model="searchParams.documentDateRange" type="daterange" align="right"
                :unlink-panels="true" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
                value-format="yyyy-MM-dd" :picker-options="pickerOptions" style="    width: 195px"></el-date-picker>
            </el-form-item>
            <el-form-item label="供应商代码">
              <el-input placeholder="请输供应商代码" v-model="searchParams.supplierCode" :clearable="true" :maxlength="11">
              </el-input>
            </el-form-item>
            <el-form-item label="供应商名称">
              <el-input placeholder="请输入供应商名称" v-model="searchParams.supplierName" :clearable="true" :maxlength="200">
              </el-input>
            </el-form-item>
            <el-form-item label="国别">
              <el-input placeholder="请输入国别" v-model="searchParams.country" :clearable="true" :maxlength="26"> </el-input>
            </el-form-item>
            <el-form-item label="DN/CN">
              <el-input placeholder="请输入DN/CN" v-model="searchParams.dnCn" :clearable="true" :maxlength="6"> </el-input>
            </el-form-item>
            <el-form-item label="GRN">
              <el-input placeholder="请输入GRN" v-model="searchParams.grn" :clearable="true" :maxlength="200"> </el-input>
            </el-form-item>
            <el-form-item label="币种">
              <el-input placeholder="请输入币种" v-model="searchParams.currency" :clearable="true" :maxlength="4"> </el-input>
            </el-form-item>
            <el-form-item label="汇率">
              <el-input placeholder="请输入汇率" v-model="searchParams.exchangeRate" :clearable="true" :maxlength="22">
              </el-input>
            </el-form-item>
            <el-form-item label="未税金额（原币）">
              <el-input placeholder="请输入未税金额（原币）" v-model="searchParams.originalCurrencyAmount" :clearable="true"
                :maxlength="18">
              </el-input>
            </el-form-item>
            <el-form-item label="未税金额（本币）">
              <el-input placeholder="请输入未税金额（本币）" v-model="searchParams.localCurrencyAmount" :clearable="true"
                :maxlength="18">
              </el-input>
            </el-form-item>
            <el-form-item label="税率">
              <el-input placeholder="请输入税率" v-model="searchParams.taxRate" :clearable="true" :maxlength="9"> </el-input>
            </el-form-item>
            <el-form-item label="税金（原币）">
              <el-input placeholder="请输入税金（原币）" v-model="searchParams.originalCurrencyTax" :clearable="true"
                :maxlength="18"> </el-input>
            </el-form-item>
            <el-form-item label="税金（本币）">
              <el-input placeholder="税金（本币）" v-model="searchParams.localCurrencyTax" :clearable="true" :maxlength="18">
              </el-input>
            </el-form-item>
            <el-form-item label="操作人" v-if="jjxs">
              <el-input placeholder="请输入操作人" v-model="searchParams.operator" :clearable="true" :maxlength="11">
              </el-input>
            </el-form-item>
            <el-form-item label="验证状态" v-if="jjxs">
              <el-input placeholder="请输入内容" v-model="searchParams.validationStatus" :clearable="true" :maxlength="26">
              </el-input>
            </el-form-item>
            <el-form-item label="操作时间" prop="operationTimeRange" v-if="jjxs">
              <el-date-picker :clearable="true" v-model="searchParams.operationTimeRange" type="daterange" align="right"
                :unlink-panels="true" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
                value-format="yyyy-MM-dd" :picker-options="pickerOptions"></el-date-picker>
            </el-form-item>
            <el-form-item label="请求号" v-if="jjxs" :maxlength="26">
              <el-input placeholder="请输入请求号" v-model="searchParams.requestNr" :clearable="true"> </el-input>
            </el-form-item>
            <el-form-item label="匹配状态" v-if="jjxs">
              <el-select v-model="searchParams.matchStatus" style="width:100%" :clearable="true">
                <el-option label="未匹配" value="0"></el-option>
                <el-option label="已匹配" value="1"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="回传状态" v-if="jjxs">
              <el-select v-model="searchParams.feedbackStatus" style="width:100%" :clearable="true">
                <el-option label="未回传" value="0"></el-option>
                <el-option label="已回传" value="1"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="回传时间" prop="feedbackTimeRange" v-if="jjxs">
              <el-date-picker :clearable="true" v-model="searchParams.feedbackTimeRange" type="daterange" align="right"
                :unlink-panels="true" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
                value-format="yyyy-MM-dd" :picker-options="pickerOptions"></el-date-picker>
            </el-form-item>
            <el-form-item style="float: right;">
              <el-button type="primary" size="mini" @click="searchFn()">查询</el-button>
              <el-button type="warning" @click="reset" size="mini" plain>重置</el-button>
              <a @click="sx()" v-show="!jjxs" style="font-size: 12px; margin-right:30px;position: relative;">更多筛选<i id=""
                  class="el-icon-arrow-down"></i></a>
              <a @click="sx()" v-show="jjxs" style="font-size: 12px;margin-right:30px;position: relative;">精简筛选<i id=""
                  class="el-icon-arrow-up"></i></a>
            </el-form-item>

          </el-form>

        </el-collapse-item>
      </el-collapse>
    </div>

    <!-- 按钮组件 -->
    <div class="btns">
      <el-button type="primary" @click="autoMatchFn()" size="small">自动匹配</el-button>
      <el-button type="primary" @click="manualMatchFn()" size="small">手工匹配</el-button>
      <el-button size="small" @click="unmatchFn()">撤销匹配</el-button>
      <el-button size="small" @click="backhaulFn()">立即回传</el-button>
    </div>
    <el-popover placement="right" width="400" trigger="click" v-model="changeColVisible">
      <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
      <div style="margin: 15px 0"></div>
      <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
        <el-checkbox v-for="city in cities" :label="city" :key="city" :disabled="city == '单据类型' || city == '单据号'">{{
          city }}</el-checkbox>
      </el-checkbox-group>
      <div>
        <el-button @click="changeColSureFn()" style="margin-top: 10%; margin-left: 80%" plain type="primary"
          size="small">确定</el-button>
      </div>
      <el-button type="text" icon="el-icon-s-grid" slot="reference" size="medium" title="自定义列表显示项"
        style="font-size: 20px;  float: right;  margin-right: 2%;"></el-button>
    </el-popover>
    <el-table :header-cell-style="{ background: '#F0F1F3', }" :data="tableData" ref="singleTable" highlight-current-row
      header-align="center" align="center" border @cell-click="clickRow" @row-dblclick="showInfo">
      <el-table-column type="selection" fixed width="45px" align="center" @change="refresh" />
      <el-table-column v-for="col in tableColList" :value="col.prop" :key="col.prop" :label="col.label" :prop="col.prop"
        :width="col.width" :sortable="col.sortable" :show-overflow-tooltip="col.showOverflowTooltip"
        :header-align="col.headerAlign">
        <template slot-scope="scope">
          <span v-if="col.canCopy">
            <span v-if="scope.row[col.prop] != '' && scope.row[col.prop] != null">
              <el-button type="text" size="small" title="点击可复制" icon="el-icon-document-copy"
                @click="handleCopyLink(scope.row[col.prop])"></el-button>
            </span>
            <span style="color:#65B9FD; cursor: pointer;" @click="showInfo(scope.row)"> {{ scope.row[col.prop] }}</span>
          </span>
          <span v-else-if="col.formatter">
            <div v-if="scope.row.matchStatus == '1'">
              <el-badge is-dot type="success" style="margin-top: 10px; margin-right: 5px"></el-badge>已匹配
            </div>
            <div v-else> <el-badge is-dot type="warning" style="margin-top: 10px; margin-right: 5px"></el-badge>未匹配</div>
          </span>
          <span v-else-if="col.formatter2">
            <div v-if="scope.row.feedbackStatus == '1'">
              <el-badge is-dot type="success" style="margin-top: 10px; margin-right: 5px"></el-badge>已回传
            </div>
            <div v-else> <el-badge is-dot type="warning" style="margin-top: 10px; margin-right: 5px"></el-badge>未回传</div>
          </span>
          <span v-else-if="col.bookNameFormatter">
            <div v-if="scope.row.validState == '1'">
              <el-badge is-dot type="success" style="margin-top: 10px; margin-right: 5px"></el-badge>有效
            </div>
            <div v-else> <el-badge is-dot type="warning" style="margin-top: 10px; margin-right: 5px"></el-badge>无效</div>
          </span>

          <span v-else>{{ scope.row[col.prop] }}</span>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页页码 -->
    <div class="pageClass">
      <el-pagination :small="true" @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="this.pageParams.pageIndex" :page-sizes="[25, 50, 75, 100]" :page-size="this.pageParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="this.pageParams.total"></el-pagination>
    </div>
    <doc_inv ref="docInv" @matchClose="matchClose"></doc_inv>
  </div>
</template>
<script>
//导入模块
import docInv from '../dialog/docInvDialog.vue'
import { feedback, getDocList, autoMatch, cancelMatch, cancelMatchOne } from '../js/zsdz.js'
import baseSearch from '@/libs/baseSearch.js'
import { getInvListFrontItem, customInvCol } from '@/api/eams/invoice_archives.js'
import { floatAdd } from "@/libs/tools.js";
import moment from 'moment'
const cityOptions = [
  '单据类型',
  '单据号',
  '单据时间',
  '供应商代码',
  '供应商名称',
  '国别',
  'BG',
  'DN/CN',
  'GRN',
  '币种',
  '汇率',
  '税率',
  '未税金额（原币）',
  '未税金额（本币）',
  '税金（原币）',
  '税金（本币）',
  '验证状态',
  '操作时间',
  '请求号',
  '匹配状态',
  '是否有效',
  '回传状态',
  '回传时间',
]
export default {
  name: 'document',
  components: {
    'doc_inv': docInv,
  },
  data() {
    return {
      activeName: '1',
      jjxs: false,
      pickerOptions: baseSearch.pickerOptions,
      // 表格数据
      tableData: [],
      tableColList: [],
      // 表格分页数据
      pageParams: {
        pageIndex: 1,
        pageSize: 25,
        total: 0,
      },
      searchParams: {
        validState: '1',
        pageSize: 25,
        pageIndex: 1,
      },
      //自定义列字段
      changeColVisible: false,
      checkAll: false,
      checkedCities: [],
      cities: cityOptions,
      isIndeterminate: true,
    }
  },
  created() {
    this.searchFn()
    this.getTabelCol()
  },
  //方法区
  methods: {
    //控制查询条件筛选
    sx() {
      this.jjxs = !this.jjxs
    },
    getTabelCol() {
      var param = {}
      param.pageName = 'zsdz'
      param.pageWindow = 'documentListColList'
      getInvListFrontItem(param).then((res) => {
        if (res.code == 0) {
          this.tableColList = res.data.invListColList
          this.checkedCities = res.data.checkColList
        }
      })
    },
    clickRow(row) {
      this.$refs.singleTable.toggleRowSelection(row)
    },
    /**
       * 查询功能
       */
    searchFn() {
      this.searchParams.pageIndex = 1
      //单据时间
      var documentDate = this.searchParams.documentDateRange;
      if (documentDate != null && documentDate != "") {
        this.searchParams.documentStartTime = documentDate[0];
        this.searchParams.documentEndTime = documentDate[1];
      } else {
        this.searchParams.documentStartTime = "";
        this.searchParams.documentEndTime = "";
      }
      //操作时间
      var operationTime = this.searchParams.operationTimeRange;
      if (operationTime != null && operationTime != "") {
        this.searchParams.operationStartTime = operationTime[0];
        this.searchParams.operationEndTime = operationTime[1];
      } else {
        this.searchParams.operationStartTime = "";
        this.searchParams.operationEndTime = "";
      }
      //回传时间
      var feedbackTime = this.searchParams.feedbackTimeRange;
      if (feedbackTime != null && feedbackTime != "") {
        this.searchParams.feedbackStartTime = feedbackTime[0];
        this.searchParams.feedbackEndTime = feedbackTime[1];
      } else {
        this.searchParams.feedbackStartTime = "";
        this.searchParams.feedbackEndTime = "";
      }
      this.initTableData()
    },
    // 查询重置功能
    reset() {
      this.searchParams = {
        pageSize: this.searchParams.pageSize,
        pageIndex: this.searchParams.pageIndex
      }
      this.$refs['form'].resetFields();
    },
    initTableData() {
      getDocList(this.searchParams).then((res) => {
        if (res.code == 0) {
          this.tableData = res.data.rows
          this.pageParams.total = Number(res.data.total)
          if (this.pageParams.total == 0) {
            this.$message({
              message: "暂无数据",
              type: 'success',
            })
          }
        } else if (res.code != 0) {
          this.$message({
            message: res.message,
            type: 'warning',
          })
        }
      })
    },
    //查看单据匹配的发票
    showInfo(row) {
      if (row.matchStatus != '1') {
        this.$message({
          message: '单据编号：' + row.documentNr + '，未匹配发票',
          type: 'warning',
        })
        return
      }
      this.$refs.docInv.searchParams.documentId = row.documentId
      this.$refs.docInv.dialogFlag = 'docInv'
      this.$refs.docInv.toolBarWidth = '100%'
      this.$refs.docInv.detailDialogVisible = true
    },
    //自动匹配
    autoMatchFn() {
      if (this.tableData == [] || this.tableData.length == 0) {
        this.$message({
          message: '无需匹配的单据列表数据',
          type: 'warning',
        })
        return
      }
      var selected = this.$refs.singleTable.selection
      if (selected == null || selected == '' || selected.length <= 0) {
        this.$message({
          message: '至少选择一条单据',
          type: 'warning',
        })
        return
      }
      var ypp = false
      var ar = new Array()
      var wx = false;
      for (let i = 0; i < selected.length; i++) {
        if (selected[i].matchStatus == '1') {
          ypp = true
          break
        }
        if (selected[i].validState != '1') {
          wx = true;
          break
        }
        ar.push(selected[i].documentId)
      }
      if (ypp) {
        this.$message({
          type: 'warning',
          message: '本次选中 ' + selected.length + ' 条单据中存在已匹配单据，请选择未匹配单据',
        })
        return
      }
      if (wx) {
        this.$message({
          type: 'warning',
          message: '本次选中 ' + selected.length + ' 条单据中存在无效单据，请选择有效单据',
        })
        return
      }
      // var ar = new Array()
      // for (var i = 0; i < selected.length; i++) {
      //   ar.push(selected[i].documentId)
      // }
      autoMatch(ar).then((res) => {
        if (res.code == 0) {
          this.$message({
            message: res.data,
            type: 'success',
          })
          this.initTableData()
        } else {
          this.$message({
            message: res.message,
            type: 'warning',
          })
        }
      })
    },
    //手工匹配
    manualMatchFn() {
      if (this.tableData == [] || this.tableData.length == 0) {
        this.$message({
          message: '无需匹配的单据列表数据',
          type: 'warning',
        })
        return
      }
      var selected = this.$refs.singleTable.selection
      if (selected == null || selected == '' || selected.length <= 0) {
        this.$message({
          message: '至少选择一条单据',
          type: 'warning',
        })
        return
      }
      if (!this.isRepeat(selected)) {
        this.$message({
          type: 'warning',
          message: '本次选中 ' + selected.length + ' 条单据中存在不同的供应商名称，请选择相同的供应商名称后再次匹配',
        })
        return
      }
      var ypp = false
      var wx = false
      let wsjehj = Number(0)
      let sjhj = Number(0)
      for (let i = 0; i < selected.length; i++) {
        if (selected[i].matchStatus == '1') {
          ypp = true
          break
        }
        if (selected[i].validState != '1') {
          wx = true;
          break
        }
        wsjehj = floatAdd(wsjehj, Number(selected[i].originalCurrencyAmount))
        sjhj = floatAdd(sjhj, Number(selected[i].originalCurrencyTax))
      }
      if (ypp) {
        this.$message({
          type: 'warning',
          message: '本次选中 ' + selected.length + ' 条单据中存在已匹配单据，请选择未匹配后再次匹配',
        })
        return
      }
      if (wx) {
        this.$message({
          type: 'warning',
          message: '本次选中 ' + selected.length + ' 条单据中存在无效单据，请选择有效单据',
        })
        return
      }
      this.$refs.docInv.wsjehj = wsjehj
      this.$refs.docInv.sjhj = sjhj
      this.$refs.docInv.documentData = selected
      this.$refs.docInv.supplierName = selected[0].supplierName
      this.$refs.docInv.dialogFlag = 'fppp'
      this.$refs.docInv.toolBarWidth = '88%'
      this.$refs.docInv.detailDialogVisible = true
    },

    matchClose() {
      this.initTableData()
    },
    isRepeat(array) {
      let names = array.map(item => item["supplierName"]);
      var set = new Set(names);
      return set.size == 1;
    },
    //撤销匹配
    unmatchFn() {
      if (this.tableData == [] || this.tableData.length == 0) {
        this.$message({
          message: '无需撤销匹配的单据列表数据',
          type: 'warning',
        })
        return
      }
      var selected = this.$refs.singleTable.selection
      if (selected == null || selected == '' || selected.length <= 0) {
        this.$message({
          message: '至少选择一条单据',
          type: 'warning',
        })
        return
      }
      var wpp = false
      var ar = new Array()
      let yhc = 0
      for (let i = 0; i < selected.length; i++) {
        if (selected[i].matchStatus == '0') {
          wpp = true
          break
        }
        if (selected[i].feedbackStatus == '1') {
          yhc++
        }
        ar.push(selected[i].documentId)
      }
      if (wpp) {
        this.$message({
          type: 'warning',
          message: '本次选中 ' + selected.length + ' 条单据中存在未匹配单据，请选择已匹配单据',
        })
        return
      }
      let tip = '本次选中已匹配单据数量：' + selected.length
      if (yhc != 0) {
        tip = tip + '，其中已回传单据数量：' + yhc
      }
      if (selected.length == 1) {
        this.$confirm(tip + "，进行撤销匹配操作吗？", '提示', {
          customClass: 'save-confirm',
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          roundButton: true
        })
          .then(() => {
            let documentId = selected[0].documentId
            var param = {}
            param.documentId = documentId
            cancelMatchOne(param).then((res) => {//单张撤销匹配
              if (res.code == 0) {
                this.$message({
                  message: res.message,
                  type: 'success',
                })
                this.initTableData()
              } else if (res.code != 0) {
                this.$message({
                  message: res.message,
                  type: 'warning',
                })
              }
            })
          })
          .catch(() => { })

      } else {
        this.$confirm(tip + "进行撤销匹配操作吗？", '提示', {
          customClass: 'save-confirm',
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          roundButton: true
        })
          .then(() => {
            cancelMatch(ar).then((res) => {//批量撤销匹配
              if (res.code == 0) {
                this.$message({
                  message: res.message,
                  type: 'success',
                })
                this.initTableData()
              } else if (res.code != 0) {
                this.$message({
                  message: res.message,
                  type: 'warning',
                })
              }
            })
          })
          .catch(() => { })

      }
    },
    //立即回传
    backhaulFn() {
      let a = new Array()
      feedback(a).then((res) => {
        if (res.code == 0) {
          this.$message({
            message: res.message,
            type: 'success',
          })
        } else if (res.code != 0) {
          this.$message({
            message: res.message,
            type: 'warning',
          })
        }
      })
    },
    //自定义列相关方法
    handleCheckAllChange(val) {
      this.checkedCities = val ? cityOptions : ['单据类型', '单据号']
      this.isIndeterminate = false
    },
    handleCheckedCitiesChange(value) {
      let checkedCount = value.length
      this.checkAll = checkedCount === this.cities.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length
    },
    changeColSureFn() {
      if (this.checkedCities.length == 0) {
        this.$message({
          type: 'warning',
          message: '请选择需要显示的列表字段',
        })
        return
      }
      var param = {}
      param.colList = this.checkedCities
      param.pageName = 'zsdz'
      param.pageWindow = 'documentListColList'
      customInvCol(param).then((res) => {
        if (res.code == 0) {
          this.changeColVisible = false
          getInvListFrontItem(param).then((res) => {
            if (res.code == 0) {
              this.tableColList = res.data.invListColList
              this.checkedCities = res.data.checkColList
              this.refresh()
            }
          })
        } else {
          this.$message({
            type: 'warning',
            message: res.message,
          })
        }
      })
    },
    refresh() {
      this.$nextTick(() => {
        this.$refs.singleTable.doLayout()
      })
    },
    ////分页
    handleSizeChange(val) {
      this.searchParams.pageSize = val
      this.initTableData()
    },
    handleCurrentChange(val) {
      this.searchParams.pageIndex = val
      this.initTableData()
    },

    handleCopyLink(val) {
      let _this = this
      this.$copyText(val).then(
        function (e) {
          _this.$message({
            showClose: true,
            message: '复制成功',
            type: 'success',
          })
        },
        function (e) {
          _this.$message({
            showClose: true,
            message: '复制失败，请手动复制',
            type: 'error',
          })
        }
      )
    },
  },
}
</script>
<style scoped>
.search-wrapper {
  text-align: left;
  box-shadow: 2px 2px 4px 2px rgba(0, 0, 0, 0.12), 0 0 6px 0 rgba(0, 0, 0, 0.04);
  margin-bottom: 25px;
}

.search-wrapper ::v-deep .el-collapse-item__content {
  padding-bottom: 0px !important;
}

.search-wrapper ::v-deep .el-collapse-item__header {
  padding-left: 15px !important;
}

.el-icon-warning {
  color: #f56c6c;
  font-size: 15px;
  margin-left: 12px;
}
</style>